<?php
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 摇奖规则
 * @author  Sameal
 */
class ErnieRuleModule extends BasicModule {

	/** @var 模块id */
	private $_moduleid;

	/** @var 条目ID */
	private $_id;

	/** @var string 表格 */
	private $_table;

	/** @var string 表格数据 */
	private $_tableData;

	/** @var 是否内容分表 */
	private $_split;

	/** @var array 可用字段 */
	private $_fields;


	/**
	 * constructor
	 * @param $moduleid
	 */
	function __construct() {
		parent::__construct();
		global $rule_table, $MOD;
		$this->_table     = $rule_table;
		$this->_split     = $MOD['split'];
		$this->_fields = array('id','name','starttime','overtime','difficulty','priority','moneyadd','used','mount','date','note','status');
    }
	public function setid($id) {
		$this->_id = $id;
	}

	public function getid() {
		return $this->_id;
	}

	public function getFields() {
		return $this->_fields;
	}

	/**
	 * 是否通过插入检测
	 * @param $post
	 * @return bool
	 */
	function pass($post) {
		if(!is_array($post)) return false;

		if(!$post['name']) return $this->err(lang('请输入奖项名称'));
		if(!(is_numeric($post['starttime'])&&($post['starttime']>=0&&$post['starttime']<=24))){
			return $this->err(lang('请输入正确开始时间0-24（正整数）'));
		}
		if(!(is_numeric($post['overtime'])&&($post['overtime']>=0&&$post['overtime']<=24))){
			return $this->err(lang('请输入正确结束时间0-24（正整数）'));
		}
		if(!(isset($post['difficulty'])&&is_numeric($post['difficulty']))){
			return $this->err(lang('请输入正确难度格式（正整数）'));
		}
		if(!(isset($post['priority'])&&is_numeric($post['priority']))){
			return $this->err(lang('请输入正确优先度格式（正整数）'));
		}
		if(!(isset($post['moneyadd'])&&is_numeric($post['moneyadd']))){
			return $this->err(lang('请输入正确奖励钱数'));
		}
		if(!(isset($post['mount'])&&is_numeric($post['mount']))){
			return $this->err(lang('请输入正确发放数量数（正整数）'));
		}
		if($post['overtime']<=$post['starttime']){
			return $this->err(lang('结束时间必须大于开始时间'));
		}
		return true;
	}

	/**
	 * 设置符合内容的值
	 * @param $post
	 * @return array|mixed
	 */
	function set($post) {
		global $MOD, $DT_TIME;

		$post['name'] = trim($post['name']);
		$post['starttime']=(isset($post['starttime'])&&is_numeric($post['starttime'])&&($post['starttime']>=0&&$post['starttime']<=24)) ? $post['starttime'] : 0;
		$post['overtime']=(isset($post['overtime'])&&is_numeric($post['overtime'])&&($post['overtime']>=0&&$post['overtime']<=24)) ? $post['overtime'] : 24;
		$post['difficulty']=(isset($post['difficulty'])&&is_numeric($post['difficulty'])) ? $post['difficulty'] : 1;
		$post['priority']=(isset($post['priority'])&&is_numeric($post['priority'])) ? $post['priority'] : 1;
		$post['moneyadd']=(isset($post['moneyadd'])&&is_numeric($post['moneyadd'])) ? $post['moneyadd'] : 0;
		$post['mount']=(isset($post['mount'])&&is_numeric($post['mount'])) ? $post['mount'] : 0;
		$post['date'] = date('Y-m-d',$DT_TIME);

		$post['note'] = stripslashes($post['note']);

		if(!defined('DT_ADMIN')) {
			$content = $post['note'];
			unset($post['note']);
			$post = Str::htmlSpecialChars($post);
			$post['note'] = Str::safe($content);
		}

		$post['note'] = addslashes($post['note']);

		return $post;
	}
	/**
	 * 获取一条数据
	 * @return array|void
	 */
	function getOne() {
		$content_table = content_table($this->_moduleid, $this->_id, $this->_split, $this->_tableData);
        return $this->_db->getOne("SELECT * FROM {$this->_table}  WHERE id=$this->_id");
	}

	/**
	 * 获取列表
	 * @param string $condition
	 * @param string $order
	 * @param string $cache
	 * @return array
	 */
	function getList($condition = 'status=3', $order = 'starttime ASC', $cache = '') {
		global $MOD,$items;
		$num = $this->_db->count($this->_table, $condition, $cache);
		$items=$num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$lists = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);

		while($r = $this->_db->fetchArray($result)) {
			$lists[] = $r;
		}
		return $lists;
	}
	/**
	 * 获取时段可用奖项
	 * @param string $condition
	 * @param string $order
	 * @param string $cache
	 * @return array
	 */
	function getPrizeList($condition = 'status=3', $order = 'starttime ASC', $cache = '') {

		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$lists = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);

		while($r = $this->_db->fetchArray($result)) {
			$lists[] = $r;
		}
		return $lists;
	}
	/**
	 * 添加数据
	 * @param $post
	 */
	function add($post) {
		global $MOD,$_userid;
		$post = $this->set($post);
		$this->_db->query(Sql::insert($this->_table, $post));
		$this->_id = $this->_db->insertId();
		return $this->_id;
	}

	/**
	 * 编辑
	 * @param $post
	 * @return bool
	 */
	function edit($post) {
		global $r, $_userid;
		$editOne=$this->getOne();
		$this->delete($this->_id, false);
		$post['used']=$editOne['used'];
		$post = $this->set($post);
		$this->_db->query(Sql::update($this->_table, $post, "id={$this->_id}", '', $this->_fields));

		EditorUpload::clearDiff($post['note'], $r['note'], $_userid);
		return true;
	}



	/**
	 * 更新
	 * @param        $id
	 * @param array  $item
	 * @param string $content
	 */
	function update($id) {
		global $DT_TIME;

		$changeRule=$this->_db->getOne("SELECT * FROM {$this->_table}  WHERE id='$id'");
		if($changeRule['date']!=date('Y-m-d',$DT_TIME)){

			$sql = "SELECT * FROM {$this->_table}";
			$sql .= " WHERE status=3";
			$sql .= " ORDER BY starttime ASC";
			$result = $this->_db->query($sql, '');
			while($r = $this->_db->fetchArray($result)) {
				$allRule[] = $r;
			}
			$allpost=array();
			foreach($allRule as $t_rule){
				$allpost[$t_rule['name']]['name']=$t_rule['name'];
				$allpost[$t_rule['name']]['date']=$t_rule['date'];
				$allpost[$t_rule['name']]['used']=intval($allpost[$t_rule['name']]['used'])+intval($t_rule['used']);
				$allpost[$t_rule['name']]['mount']=intval($allpost[$t_rule['name']]['used'])+intval($t_rule['mount']);
				$allpost[$t_rule['name']]['printmoney']=intval($allpost[$t_rule['name']]['printmoney'])+intval($t_rule['used'])*intval($t_rule['moneyadd']);
				$date=date('Y-m-d',$DT_TIME);
				$this->_db->query("UPDATE $this->_table SET used=0,date='$date' WHERE id={$t_rule['id']}");
			}
			foreach($allpost as $post){
				$this->_db->query(Sql::insert('xd_ernieprizelog', $post));
			}
		}
		$this->_db->query("UPDATE $this->_table SET used=used+1 WHERE id='$id'");
	}

	/**
	 * 回收站
	 * @param $id
	 * @return bool
	 */
	function recycle($id) {
		if(is_array($id)) {
			foreach($id as $v) { $this->recycle($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=0","id=$id"));
			$this->delete($id, false);
			return true;
		}		
	}

	/**
	 * 还原
	 * @param $id
	 * @return bool
	 */
	function restore($id) {
		global $module, $MOD;
		if(is_array($id)) {
			foreach($id as $v) { $this->restore($v); }
		} else {
			$this->_db->query(Sql::update($this->_table,"status=3","id=$id"));
			return true;
		}		
	}

	/**
	 * 删除条目
	 * @param      $id
	 * @param bool $all
	 */
	function delete($id, $all = true) {
		if(is_array($id)) {
			foreach($id as $v) {
				$this->delete($v, $all);
			}
		} else {
			$this->_id = $id;
			$r = $this->getOne();
			if($all) {
				$this->_db->query(Sql::delete($this->_table,"id=$id"));
			}
		}
	}

	/**
	 * 清空回收站内容
	 * @param string $condition
	 */
	function clear($condition = 'status=0') {		
		$result = $this->_db->query("SELECT id FROM {$this->_table} WHERE $condition ");
		while($r = $this->_db->fetchArray($result)) {
			$this->delete($r['id']);
		}
	}

}
